package my.sorter.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import my.sorter.bean.EmergencyCase;
import my.sorter.bean.MyEmail;
import my.sorter.bean.MyPageInfo;
import my.sorter.bean.filter.EmergencyCaseFilter;
import my.sorter.service.SortService;
import my.sorter.translator.out.MyMessage;
import my.sorter.utils.ExcelUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

/**
 * @author zyf10
 */
@Controller
public class ReportController {
    @Autowired
    SortService sortService;

    /**
     * 获取病例完整信息
     *
     * @param filter
     * @param myPageInfo
     * @return
     */
    @RequiresPermissions(value = {"admin","diseaseJudge","signJudge"},logical = Logical.OR)
    @GetMapping("/report/get")
    @ResponseBody
    public Object getReportData(EmergencyCaseFilter filter, MyPageInfo myPageInfo,String dNames) {
        if (!StringUtils.isEmpty(dNames)){
            JSONArray detailArray = JSON.parseArray(dNames);
            if (detailArray.size()>0){
                List<String> detailNames = Collections.synchronizedList(new ArrayList<>());
                for (Object detail:detailArray.toArray()){
                    detailNames.add(detail.toString());
                }
                filter.setDetailNames(detailNames);
            }
        }
        PageHelper.startPage(myPageInfo.getCurrentPage(), myPageInfo.getPageSize());
        List<EmergencyCase> emergencyCases = sortService.getDiagnoses(filter);
        PageInfo pageInfo = new PageInfo(emergencyCases);
        myPageInfo.setTotal((new Long(pageInfo.getTotal()).intValue()));
        myPageInfo.setTotalPage(pageInfo.getPages());
        return MyMessage
                .successMessage(myPageInfo)
                .addMessage("获取病例完整信息成功")
                .addData(emergencyCases);
    }

    @RequiresPermissions("admin")
    @PostMapping("/report/send")
    @ResponseBody
    public Object sendEmail(String email) {
        JSONObject emailJson = JSON.parseObject(email);
        MyEmail myEmail = new MyEmail();
        myEmail.setTitle(emailJson.get("title").toString());
        JSONArray addressArray = emailJson.getJSONArray("address");
        List<String> addressList = Collections.synchronizedList(new ArrayList<>());
        for (Object address : addressArray.toArray()) {
            addressList.add(address.toString());
        }
        myEmail.setAddress(addressList);
        myEmail.setContent(emailJson.get("content").toString());
        Boolean flag = sortService.sendEmail(myEmail);
        return flag ? MyMessage.successMessage("通报邮件发送成功") : MyMessage.failMessage("通报邮件发送失败");
    }

    @RequiresPermissions(value = {"admin","diseaseJudge","signJudge"},logical = Logical.OR)
    @GetMapping("/report/export")
    public void exportReport(String dNames,
                             HttpServletResponse response,
                             EmergencyCaseFilter filter) {
        if (!StringUtils.isEmpty(dNames)){
            JSONArray detailArray = JSON.parseArray(dNames);
            if (detailArray.size()>0){
                List<String> detailNames = Collections.synchronizedList(new ArrayList<>());
                for (Object detail:detailArray.toArray()){
                    detailNames.add(detail.toString());
                }
                filter.setDetailNames(detailNames);
            }
        }
        List<EmergencyCase> emergencyCases = sortService.getDiagnoses(filter);


        List<Map<String, Object>> data = new ArrayList<>();
        List<String> names = new ArrayList<>();
        for (EmergencyCase emergencyCase : emergencyCases) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("pName", emergencyCase.getpName());
            map.put("idNumber", emergencyCase.getIdNumber());
            map.put("vitalSigns", emergencyCase.getVitalSigns());
            map.put("consciousness", emergencyCase.getConsciousness());
            map.put("pain", emergencyCase.getPain());
            map.put("anaphylaxis", emergencyCase.getAnaphylaxis());
            map.put("pressureScore", emergencyCase.getPressureSore());
            data.add(map);
        }
        names.add("病人姓名");
        names.add("身份证号");
        names.add("生命体征");
        names.add("意识");
        names.add("疼痛");
        names.add("过敏史");
        names.add("压疮");
        Workbook wb = ExcelUtils.export(data, names, "急诊情况报表");
        try {
            response.setHeader("Content-Disposition", "attachment; filename=report.xls");
            response.setContentType("application/vnd.ms-excel; charset=utf-8");
            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
